<template>
  <div class="app-container">

    <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
      <el-form-item slot="button">
        <el-button v-hasPermi="['channel:channelData:add']" type="success" @click="handleAdd">添加渠道</el-button>
      </el-form-item>
      <template slot="selectRemote" slot-scope="{param}">
        <template v-if="param === 'video_id'">
          <YxhySelectRemote
            :value.sync="queryParams.video_id"
            :request-fn="queryNonSortLibrary"
            :request-key="`title_search`"
            :response-id="`library_id`"
            :response-name="`title`"
            :placeholder="`请选择推广短剧`"
          />
        </template>
        <template v-if="param === 'admin_id'">
          <YxhySelectRemote
            :value.sync="queryParams.admin_id"
            :request-fn="queryUserAllList"
            :request-key="`name_search`"
            :response-id="`id`"
            :response-name="`chinese_name`"
            :placeholder="`请选择操作人`"
          />
        </template>
      </template>
    </YxhyTableQuery>

    <YxhyTableData :columns="columns" :data="tableList" :loading="loading">
      <!-- 渠道ID插槽 -->
      <template #id>
        <el-table-column label="" align="center" width="160">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">渠道ID</p>
            <p class="font-color-th">渠道名</p>
            <p class="font-color-th">创建时间</p>
            <p class="font-color-th">账户ID</p>
          </template>
          <template slot-scope="scope">
            <p>{{ scope.row.id }}</p>
            <p class="detail-hover" @click="handleShowDetail(scope.row)">{{ scope.row.name }}</p>
            <p>{{ scope.row.created_at }}</p>
            <p v-for="(item, index) in scope.row.channel_ad" :key="index">
              <span v-if="item.flag === 1" class="font-bold">{{ item.ad_id }}</span>
            </p>
            <el-button v-hasPermi="['channel:channelData:bind']" type="success" size="mini" @click="handleShowBinding(scope.row)">绑定账户ID</el-button>
          </template>
        </el-table-column>
      </template>
      <!-- 链接插槽 -->
      <template #link>
        <el-table-column label="复制链接" align="center" width="110">
          <template slot-scope="{ row }">
            <div class="flex flex-column link-panel">
              <template v-if="row.isDouYin">
                <el-button type="primary" size="mini" @click="handleDyUrlLink(row)">线索短链</el-button>
                <el-button type="primary" size="mini" @click="handleDyStartUrl(row)">抖小启动页</el-button>
                <el-button type="primary" size="mini" @click="handleDyStartParam(row)">抖小启动参数</el-button>
              </template>
              <template v-else>
                <el-button type="success" size="mini" @click="handleCopy(row.short_url)">线索短链</el-button>
                <el-button type="success" size="mini" @click="handleCopy(row.floor_page_url)">小程序路径</el-button>
                <el-button type="success" size="mini" @click="handleCopy(row.monitoring_url)">监测链接</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </template>
      <!-- 抖音链接插槽 -->
      <template #dyLink>
        <el-table-column label="抖音链接" align="center" width="110">
          <template slot-scope="{ row }">
            <div class="flex flex-column link-panel">
              <el-button type="primary" size="mini" @click="handleDyUrlLink(row)">抖小短链</el-button>
              <el-button type="primary" size="mini" @click="handleDyStartUrl(row)">抖小启动页</el-button>
              <el-button type="primary" size="mini" @click="handleDyStartParam(row)">抖小启动参数</el-button>
            </div>
          </template>
        </el-table-column>
      </template>
      <!-- 推广短剧插槽 -->
      <template #library>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">推广短剧</p>
            <p class="font-color-th">进入剧集</p>
          </template>
          <template slot-scope="scope">
            <p>{{ scope.row.video_name }}</p>
            <p>{{ scope.row.episode_name }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 推广点击数插槽 -->
      <template #clickNumber>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">展示数</p>
            <p class="font-color-th">点击数</p>
            <p class="font-color-th">点击转化率</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ row.channel_statistics.show_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.click_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.click_rate | domEmpty }}%</p>
          </template>
        </el-table-column>
      </template>
      <!-- 用户数插槽 -->
      <template #userNumber>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">用户数</p>
            <p class="font-color-th">充值转化率</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ row.channel_statistics.user_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.recharge_rate | domEmpty }}%</p>
          </template>
        </el-table-column>
      </template>
      <!-- 关注数插槽 -->
      <!--      <template #followNumber>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">关注数</p>
            <p class="font-color-th">关注成本</p>
            <p class="font-color-th">关注率</p>
          </template>
          <p>xxxx</p>
          <p>xxxx</p>
          <p>xxxx</p>
        </el-table-column>
      </template>-->
      <!-- 总订单数插槽 -->
      <template #orderNumber>
        <el-table-column align="center" width="140">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">总订单数</p>
            <p class="font-color-th">VIP订单数（占比）</p>
            <p class="font-color-th">充值人数</p>
            <p class="font-color-th">完成率</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ row.channel_statistics.order_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.vip_order_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.recharge_user_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.complete_order_rate | domEmpty }}%</p>
          </template>
        </el-table-column>
      </template>
      <!-- 平台回传数插槽 -->
      <template #platformBackNumber>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">平台回传数</p>
            <p class="font-color-th">平台转化成本</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ row.channel_statistics.report_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.report_cost | domEmpty }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 实际回传数插槽 -->
      <template #realityBackNumber>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">实际回传数</p>
            <p class="font-color-th">实际转化成本</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ row.channel_statistics.actual_report_num | domEmpty }}</p>
            <p>{{ row.channel_statistics.actual_report_cost | domEmpty }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 消耗成本插槽 -->
      <template #consumeCost>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">消耗成本</p>
            <p class="font-color-th">充值金额</p>
            <p class="font-color-th">回款率</p>
            <p class="font-color-th">人均充值金额</p>
          </template>
          <template slot-scope="{ row }">
            <p>￥{{ row.channel_statistics.consumption_cost | domEmpty }}</p>
            <p>￥{{ row.channel_statistics.recharge_amount | domEmpty }}</p>
            <p>{{ row.channel_statistics.recovery_rate | domEmpty }}%</p>
            <p>￥{{ row.channel_statistics.per_capita_recharge | domEmpty }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 投放平台插槽 -->
      <template #launchPlatform>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">投放平台</p>
            <!--            <p class="font-color-th">投放状态</p>-->
            <p class="font-color-th">关联小程序</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ DELIVERY_PLATFORM[row.delivery_platform] }}</p>
            <!--            <p>{{ row.channel_statistics.delivery_status | domEmpty }}</p>-->
            <p>{{ row.product_name | domEmpty }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 操作人插槽 -->
      <template #admin_username>
        <el-table-column align="center" width="auto">
          <template
            slot="header"
            slot-scope="{ column, $index }"
          >
            <p class="font-color-th">操作人</p>
            <p class="font-color-th">投放状态</p>
          </template>
          <template slot-scope="{ row }">
            <p>{{ row.admin_username }}</p>
            <p>{{ STATUS[row.status] }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <el-button v-hasPermi="['channel:channelData:edit']" type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <template v-if="scope.row.status === 1">
                <el-button v-hasPermi="['channel:channelData:status']" type="info" size="mini" @click="handleLapse(scope.row)">停投</el-button>
              </template>
              <template v-else-if="scope.row.status === 2">
                <el-button v-hasPermi="['channel:channelData:status']" type="primary" size="mini" @click="handleLapse(scope.row)">恢复</el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!--  详情弹出层  -->
    <el-dialog
      title="渠道详情"
      :visible.sync="showDetail"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="detailForm" label-width="100px">
        <el-form-item label="渠道名">
          <p class="detail-text">{{ detailForm.name }}</p>
        </el-form-item>
        <el-form-item label="渠道ID">
          <p class="detail-text">{{ detailForm.id }}</p>
        </el-form-item>
        <template v-if="detailForm.flag === 0">
          <el-form-item label="账户解绑时间">
            <p class="detail-text">{{ detailForm.unbinding_time | domEmpty }}</p>
          </el-form-item>
        </template>
        <el-form-item label="账户ID">
          <p v-for="(item, index) in detailForm.channel_ad" :key="index" class="detail-text">
            <span :class="item.flag === 1 ? '' : 'font-color-3'">{{ item.ad_id }}</span>
          </p>
        </el-form-item>
        <el-form-item label="创建人">
          <p class="detail-text">{{ detailForm.admin_username | domEmpty }}</p>
        </el-form-item>
        <el-form-item label="剧集">
          <p class="detail-text">{{ detailForm.video_name }} - {{ detailForm.episode_name }}</p>
        </el-form-item>
        <el-form-item label="充值模板">
          <p class="detail-text">{{ detailForm.pay_temp_name }}</p>
        </el-form-item>
        <el-form-item label="回传配置">
          <p class="detail-text">{{ detailForm.report_config_name }}</p>
        </el-form-item>
        <el-form-item label="创建时间">
          <p class="detail-text">{{ detailForm.created_at }}</p>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleShowDetail">关闭</el-button>
      </div>
    </el-dialog>

    <!--  绑定账户ID弹出层  -->
    <el-dialog
      title="绑定账户ID"
      :visible.sync="showBinding"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="bindingFormRef"
        :model="bindingForm"
        :rules="bindingRules"
        label-width="80px"
        @submit.native.prevent=""
      >
        <el-form-item label="账户ID" prop="ad_id">
          <el-input v-model="bindingForm.ad_id" type="number" maxlength="20" placeholder="请输入账户ID" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleShowBinding">取 消</el-button>
        <el-button type="primary" @click="handleBinding">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { ADV_REPORT_TYPE } from '@/api/config/channelPostBack.js'
import { columnsStatic } from './Ds.js'
import {
  DELIVERY_PLATFORM, getDyUrlLink,
  queryPageChannelDataList, STATUS,
  updateChannelAdId,
  updateChannelStatus
} from '@/api/channel/channelData'
import { queryNonSortLibrary } from '@/api/video/library'
import { queryUserAllList } from '@/api/system/account'

export default {
  name: 'ChannelList',
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
        id: undefined,
        name: undefined,
        video_id: undefined,
        ad_id: undefined,
        admin_id: undefined,
        applet_type: undefined
      },
      // 查询表单
      queryColumns: [{
        label: '',
        placeholder: '请输入渠道Id',
        type: 'input',
        param: 'id'
      }, {
        label: '',
        placeholder: '请输入渠道名称',
        type: 'input',
        param: 'name'
      },
      {
        label: '',
        placeholder: '请选择推广短剧',
        type: 'selectRemote',
        param: 'video_id'
      },
      {
        label: '',
        placeholder: '请输入账户ID',
        type: 'input',
        param: 'ad_id'
      },
      {
        label: '',
        placeholder: '请选择操作人',
        type: 'selectRemote',
        param: 'admin_id'
      },
      {
        label: '',
        placeholder: '请选择种类',
        type: 'select',
        selectOptions: [
          { name: '微小投放', value: 1 },
          { name: '抖小投放', value: 4 }
          // { name: '安卓', value: 2 },
          // { name: 'IOS', value: 3 }
        ], // 下拉框选项
        param: 'applet_type' // 表单数据项
      }],
      loading: false,
      // 表格列
      columns: columnsStatic,
      ADV_REPORT_TYPE,
      DELIVERY_PLATFORM,

      showBinding: false,
      bindingForm: {
        ad_id: undefined,
        id: undefined,
        confirm: undefined
      },
      bindingRules: {
        ad_id: [
          { required: true, message: '请输入账户ID', trigger: ['blur', 'change'] }
        ]
      },
      showDetail: false,
      detailForm: {},
      queryNonSortLibrary,
      queryUserAllList
    }
  },
  computed: {
    STATUS() {
      return STATUS
    }
  },
  created() {
    this.init()
  },
  methods: {
    /** 保留两位小数，不四舍五入 */
    reserveNumberTow(number) {
      return Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(number)
    },
    /** 转化百分比 */
    percentageCompute(number) {
      const ratioVal = number * 100
      return Intl.NumberFormat('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(ratioVal)
    },
    async init() {
      this.loading = true
      const res = await queryPageChannelDataList({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.forEach(e => {
        e.channel_statistics.consumption_cost = this.reserveNumberTow(e.channel_statistics.consumption_cost)
        e.channel_statistics.click_rate = this.percentageCompute(e.channel_statistics.click_rate)
        e.channel_statistics.recharge_rate = this.percentageCompute(e.channel_statistics.recharge_rate)
        e.channel_statistics.complete_order_rate = this.percentageCompute(e.channel_statistics.complete_order_rate)
        e.channel_statistics.recovery_rate = this.percentageCompute(e.channel_statistics.recovery_rate)
        e.admin_username = e.admin_username || '-'
        e.channel_ad = e.channel_ad || []
        e.isDouYin = e.product_name.indexOf('字节') !== -1
      })
      console.log(res.data)
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 清空搜索按钮操作 */
    handleClear() {
      this.init()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: '/channel/channelData/add'
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { id } = row
      this.$router.push({
        path: '/channel/channelData/add',
        query: {
          id
        }
      })
    },
    /** 失效/恢复按钮操作 */
    handleLapse(row) {
      const { id, status } = row
      const transStatus = status === 1 ? 2 : 1
      const confirmTitle = status === 1 ? '确定要停投吗？' : '确定要恢复投放吗？'
      this.$modal
        .confirm(confirmTitle)
        .then(function() {
          return updateChannelStatus({
            id,
            status: transStatus// 状态 1-有效 0-失效
          })
        })
        .then(() => {
          this.init()
          this.$modal.msgSuccess('操作成功')
        })
        .catch(() => {})
    },
    handleShowDetail(row) {
      this.detailForm = row
      this.showDetail = !this.showDetail
    },
    handleShowBinding(row) {
      const { id } = row
      if (id) {
        this.bindingForm.id = id
      }

      this.resetForm('bindingFormRef')
      this.showBinding = !this.showBinding
    },
    /** 绑定账户ID */
    handleBinding() {
      this.$refs['bindingFormRef'].validate((valid) => {
        if (valid) {
          updateChannelAdId(this.bindingForm).then(() => {
            this.bindingForm = {
              ad_id: undefined,
              id: undefined,
              confirm: undefined
            }
            this.resetForm('bindingFormRef')
            this.showBinding = false
            this.$modal.msgSuccess('账户ID修改成功')
            this.reset
            this.init()
          }).catch((res) => {
            this.confirmBinding()
          })
        }
      })
    },
    /** 账户ID已存在，确定提示绑定*/
    confirmBinding() {
      const _this = this
      this.bindingForm.confirm = 1
      this.$modal
        .confirm('是否解除之前的绑定吗？')
        .then(function() {
          _this.handleBinding()
        })
        .catch(() => {})
    },
    /** 复制链接 */
    handleCopy(url) {
      // 创建一个input框
      const input = document.createElement('input')
      // 将指定的DOM节点添加到body的末尾
      document.body.appendChild(input)
      // 设置input框的value值为复制的值
      const address = url
      input.setAttribute('value', address)
      // 选取文本域中的内容
      input.select()
      // copy的意思是拷贝当前选中内容到剪贴板
      // document.execCommand（）方法操纵可编辑内容区域的元素
      // 返回值为一个Boolean，如果是 false 则表示操作不被支持或未被启用
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        this.$modal.msgSuccess('复制成功')
      }
      // 删除这个节点
      document.body.removeChild(input)

      // 需要https访问才能使用
      // navigator.clipboard.writeText(url).then(() => {
      //   this.$modal.msgSuccess('链接复制成功')
      // }).catch(error => {
      //   // 如果用户没有授权，会抛出错误
      //   console.error('cannot copy this text,the error is :', error)
      // })
    },
    /** 抖小短链按钮 */
    async handleDyUrlLink(row) {
      const { id } = row
      const data = await getDyUrlLink({
        id
      })
      const { url } = data
      this.handleCopy(url)
    },
    /** 抖小启动页按钮 */
    handleDyStartUrl(row) {
      const { floor_page_url } = row
      let url = floor_page_url.split('?')[0]
      // 去掉第一个/
      url = url.substring(1, url.length)
      this.handleCopy(url)
    },
    /** 抖小启动参数按钮 */
    handleDyStartParam(row) {
      const { floor_page_url } = row
      const url = floor_page_url.split('?')[1]
      this.handleCopy(url)
    }
  }
}
</script>

<style lang="scss" scoped>
.link-panel .el-button + .el-button{
  margin-left: 0;
  margin-top: 10px;
}
.item-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
  .item-panel {
    width: 32%;
    background-color: #f8f8f8;
    padding: 10px;
    margin-bottom: 20px;
  }
}
.item-box:after {
  content: '';
  width: 30%;
}

.detail-hover {
  color: #409eff
}

.detail-hover:hover {
  cursor: pointer;
}

.detail-text {
  margin-left: 20px;
}
</style>
